package com.yjymm.config;

import javafx.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author yjymm
 * @date 2020-04-12 11:18
 */

@EnableConfigurationProperties(MyCustomProperties.class)
public class CustomerAutoConfig {

    @Autowired
    private MyCustomProperties myCustomProperties;

    @Bean
    @ConditionalOnProperty(prefix = "yjymm.auto",name = "enabled",havingValue = "true")
    public CommandLineRunner creatCommandLineRunner(Environment env){
            return new MyCommandLineRunner(env);
    }


    @Bean("applicationEventMulticaster")
    public ApplicationEventMulticaster createApplicationEventMulticaster(ThreadPoolTaskExecutor taskExecutor){
        SimpleApplicationEventMulticaster simpleAp = new SimpleApplicationEventMulticaster();
        simpleAp.setTaskExecutor(taskExecutor);
        return simpleAp;
    }

    public static class MyNoticeEvent extends ApplicationEvent {
        private final Logger logger = LoggerFactory.getLogger(MyNoticeEvent.class);

        private String message;

        public MyNoticeEvent(String message) {
            super(message);
            this.message = message;
            logger.info("添加自定义事件成功  message = "+ message);
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }


    @Component
    public static class MyNoticeListener implements ApplicationListener<MyNoticeEvent>{
        private final Logger logger = LoggerFactory.getLogger(MyNoticeListener.class);

        @Override
        public void onApplicationEvent(MyNoticeEvent myNoticeEvent) {
            logger.info("自定义事件监听器监听到 MyNoticeEvent");
            logger.info("当前线程 ："+ Thread.currentThread().getName()+"睡眠 2 秒");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("MyNoticeEvent 的message 属性值: "+ myNoticeEvent.getMessage());
        }
    }



}
